package com.file.upload.util;

import com.file.upload.entity.FileChunk;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.List;

/**
 * @Description
 * @Author lhj
 * @Date 2025/4/23 21:29
 */
@Slf4j
public class FileUtils {

    /**
     * 计算文件的MD5值
     */
    public static String calculateMd5(File file) throws IOException {
        try (FileInputStream fis = new FileInputStream(file)) {
            return DigestUtils.md5DigestAsHex(fis);
        }
    }

    /**
     * 合并文件分片
     */
    public static void mergeFiles(List<FileChunk> chunks, String targetFile) throws IOException {
        try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile))) {
            // 按分片序号排序
            chunks.sort(Comparator.comparing(FileChunk::getChunkNumber));

            // 1MB buffer
            byte[] buffer = new byte[1024 * 1024]; 
            int len;

            for (FileChunk chunk : chunks) {
                try (BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(Paths.get(chunk.getChunkPath())))) {
                    while ((len = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, len);
                    }
                }
            }

            outputStream.flush();
        }
    }

    /**
     * 递归删除目录
     */
    public static void deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }
            directory.delete();
        }
    }
}